import { Directive, OnInit, Input, ElementRef, OnDestroy } from '@angular/core';
import { BaseView } from '../../core/view/base-view';
import { LazyLoaderService } from '../../core/service/lazy-loader.service';

@Directive({
  selector: '[bzClipboard]'
})
export class ClipboardDirective<U, B, S> extends BaseView<U, B, S> implements OnInit, OnDestroy {

  // tslint:disable-next-line:no-input-rename
  @Input('bzClipboard') text: string;
  @Input() bzClipboardAction = 'copy';

  private clipboard = null;

  constructor(
    private ele: ElementRef,
    private lazyLoaderService: LazyLoaderService
  ) {
    super();
  }

  ngOnInit(): void {
    this.lazyLoaderService.load('clipboard', this.init.bind(this));
  }

  ngOnDestroy(): void {
    this.clipboard.destroy();
    this.clipboard = null;
  }

  private init() {
    this.clipboard = new (<any>window).ClipboardJS(this.ele.nativeElement, {
      action: this.bzClipboardAction,
      text: (trigger) => {
        return this.text;
      }
    });
    this.clipboard.on('success', (e) => {
      const msg = this.i18nService.getValue('@nrfzcg');
      this.messageService.success(msg);
    });
    this.clipboard.on('error', (e) => {
      const msg = this.i18nService.getValue('@nrfzsb');
      this.messageService.success(msg);
    });
  }


}
